/*****************************************************************************************
 **  Author:COCO 2022
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import modelFooter from './quality_extend/Base_MaterialDetailModelBody.vue'
import modelBody from './quality_extend/WorkOrderModelBody.vue'
import modelHeader from './quality_extend/ProcessModelBody.vue'
import gridHeader from './quality_extend/GridHeader.vue'
let extension = {
  data() {
    return {
      Id: '',
    }
  },
  components: {
    //查询界面扩展组件
    gridHeader,
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody: modelBody,
    modelFooter: modelFooter,
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    onInit() {
      //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });

      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;
      //显示序号(默认隐藏)

      this.columnIndex = true
      // this.single = true
      this.boxOptions.labelWidth = 120
      let { permission } = this.$store.getters.getPermission(
        '/Quality_ProcessCheck'
      )

      //选择数据源功能
      this.editFormOptions.forEach((x) => {
        x.forEach((item) => {
          // console.log(item)
          if (item.field == 'WorkOrderCode') {
            //给编辑表单设置[选择数据]操作,extra具体配置见mesform组件api
            item.extra = {
              icon: 'el-icon-zoom-out',
              text: '选择',
              style: 'color:blue;font-size: 14px;cursor: pointer;',
              click: (item) => {
                this.$refs.modelBody.open()
              },
            }
          }
          if (item.field == 'ProductCode') {
            //给编辑表单设置[选择数据]操作,extra具体配置见mesform组件api
            item.extra = {
              icon: 'el-icon-zoom-out',
              text: '选择',
              style: 'color:blue;font-size: 14px;cursor: pointer;',
              click: (item) => {
                this.$refs.modelFooter.open()
              },
            }
          }
          if (item.field == 'ProcessCode') {
            //给编辑表单设置[选择数据]操作,extra具体配置见mesform组件api
            item.extra = {
              icon: 'el-icon-zoom-out',
              text: '选择',
              style: 'color:blue;font-size: 14px;cursor: pointer;',
              click: (item) => {
                this.$refs.modelHeader.open()
              },
            }
          }

          if (item.field == 'DisStandNumber' || 'StandNumber' || 'ScrapQty') {
            item.required = true
          }

          if (item.field == 'ScrapQty') {
            item.onChange = (value) => {
              // console.log(value);
              if (value <= 0) {
                this.editFormOptions.forEach((item) => {
                  item.forEach((x) => {
                    if (x.field == 'reason') {
                      x.hidden = true
                      x.required = false
                    }
                  })
                })
              } else {
                this.editFormOptions.forEach((item) => {
                  item.forEach((x) => {
                    if (x.field == 'reason') {
                      x.hidden = false
                      x.required = true
                    }
                  })
                })
              }
            }
          }

          if (item.field == 'CheckDate') {
            item.required = false
          }
        })
      })

      this.editFormOptions[this.editFormOptions.length - 1].push(
        {
          title: '责任部门',
          field: 'reason',
          type: 'input',
          required: true,
          hidden: true,
        },
        {
          title: '备注',
          field: 'remark',
          type: 'textarea',
        }
      )

      this.columns.some((item) => {
        if (item.field == 'ProcessCheckName') {
          item.link = false
          return true
        }
      })

      this.columns.unshift({
        title: '操作',
        field: 'action',
        render: (h, { row, column }) => {
          let dom = ''
          if (permission.includes('Update')) {
            if (row.Status == 0) {
              dom = (
                <el-link
                  type="primary"
                  underline={false}
                  onClick={() => {
                    this.linkData(row, column)
                    this.Id = row.ProcessCheckId
                  }}
                >
                  审核
                </el-link>
              )
            }
          }

          return dom
        },
      })

      this.buttons.forEach((item) => {
        if (item.value == 'Update') {
          item.hidden = true
        }

        // if (item.value == 'Audit') {
        //   item.onClick = () => {
        //     let selectList = this.$refs.table.getSelected()
        //     if (selectList.length == 0)
        //       return this.$message.error('请选择一条数据')
        //     let noStandard = selectList.find((item) => item.Status !== 0)
        //     if (noStandard == undefined) {
        //       this.$refs.gridHeader.open({
        //         Title: '质检',
        //         Columns: [
        //           {
        //             title: '检验单名称',
        //             field: 'ProcessCheckName',
        //           },
        //           {
        //             title: '检验单编码',
        //             field: 'ProcessCheckCode',
        //           },
        //           {
        //             title: '产品名称',
        //             field: 'ProductName',
        //           },
        //           {
        //             title: '产品编码',
        //             field: 'ProductCode',
        //           },
        //           {
        //             title: '工序',
        //             field: 'ProcessName',
        //           },
        //           {
        //             title: '报工合格数量',
        //             field: 'CrQuantity',
        //           },
        //           {
        //             title: '报工不良数量',
        //             field: 'MajQuantity',
        //           },
        //           {
        //             title: '报工报废数量',
        //             field: 'MinQuantity',
        //           },
        //           {
        //             title: '质检合格数量',
        //             field: 'StandNumber',
        //             required: true,
        //             edit: {
        //               type: 'number',
        //             },
        //           },
        //           {
        //             title: '质检不良数量',
        //             field: 'DisStandNumber',
        //             required: true,
        //             edit: {
        //               type: 'number',
        //             },
        //           },
        //           {
        //             title: '质检报废数量',
        //             field: 'ScrapQty',
        //             required: true,
        //             edit: {
        //               type: 'number',
        //             },
        //           },
        //         ],
        //         TableData: selectList,
        //         saveFun: async (tableData) => {
        //           try {
        //             tableData = tableData.map((item) => {
        //               if (
        //                 item.StandNumber == null ||
        //                 item.StandNumber == undefined ||
        //                 item.StandNumber == ''
        //               )
        //                 throw new Error('请输入质检合格数量')

        //               if (
        //                 item.DisStandNumber == null ||
        //                 item.DisStandNumber == undefined ||
        //                 item.DisStandNumber == ''
        //               )
        //                 throw new Error('请输入质检不良数量')
        //               if (
        //                 item.ScrapQty == null ||
        //                 item.ScrapQty == undefined ||
        //                 item.ScrapQty == ''
        //               )
        //                 throw new Error('请输入质检报废数量')
        //               return {
        //                 ...item,
        //                 id: item.ProcessCheckId,
        //               }
        //             })

        //             let res = await this.http.post(
        //               'api/Production_ReportWorkOrder/ReportCheck',
        //               tableData,
        //               true
        //             )
        //             if (res.status) {
        //               this.$message.success('质检成功')
        //               this.search()
        //               return true
        //             } else {
        //               this.$message.error(res.message)
        //               return false
        //             }
        //           } catch (err) {
        //             this.$message.error(err.message)
        //           }
        //         },
        //       })
        //     } else {
        //       this.$message.error('请选择未审批的检验单')
        //     }
        //   }
        // }
      })

      this.boxButtons.forEach((item) => {
        if (item.value == 'save') {
          item.onClick = async () => {
            let {
              DisStandNumber: disStandNumber,
              StandNumber: standNumber,
              ScrapQty: scrapQty,
              reason,
              remark,
            } = this.editFormFields

            if (disStandNumber === '')
              return this.$message.error('请输入不合格数')
            if (standNumber === '') return this.$message.error('请输入合格数')
            if (scrapQty === '') return this.$message.error('请输入报废数')
            if (scrapQty !== '' && scrapQty > 0) {
              if (reason == '' || reason == undefined) {
                return this.$message.error('请输入责任部门')
              }
            }

            let param = {
              disStandNumber,
              standNumber,
              scrapQty,
              reason,
              remark,
            }

            let res = await this.http.post(
              `/api/Production_ReportWorkOrder/ReportCheck?Id=${this.Id}`,
              param,
              true
            )

            if (res.status) {
              this.$message.success('保存成功')
              this.editFormFields.DisStandNumber = 0
              this.editFormFields.StandNumber = 0
              this.editFormFields.ScrapQty = 0
              this.editFormFields.reason = ''
              this.editFormFields.remark = ''
              this.boxModel = false
              this.search()
            } else {
              this.$message.error(res.message)
            }
          }
        }
      })
    },
    getRow(_rows) {
      this.editFormFields['Product_Id'] = _rows[0].Product_Id
      this.editFormFields['ProductName'] = _rows[0].ProductName
      this.editFormFields['ProductCode'] = _rows[0].ProductCode
      this.editFormFields['ProductStandard'] = _rows[0].ProductStandard
      let url =
        'api/Quality_TemplateTestItem/getProcessTestItemRows?ProductId=' +
        _rows[0].Product_Id
      this.http.get(url, {}, true).then((rows) => {
        if (rows == '[]') {
          this.$refs.detail.rowData = []
        } else {
          let newArr = rows.map((val) => {
            let json = {}
            json.CheckMethod = val.CheckMethod
            json.TestItemCode = val.TestItemCode
            json.QCTool = val.QCTool
            json.StanderValue = val.StanderValue
            json.TemplateId = val.TemplateId
            json.TemplateTestItemId = val.TemplateTestItemId
            json.TestItemId = val.TestItemId
            json.TestItemName = val.TestItemName
            json.TestItemType = val.TestItemType
            json.ThresholdMax = val.ThresholdMax
            json.ThresholdMin = val.ThresholdMin
            return json
          })
          this.$refs.detail.rowData = newArr
        }
      })
    },
    getRowWorkOrder(_rows) {
      this.editFormFields['WorkOrderCode'] = _rows[0].WorkOrderCode
      this.editFormFields['WorkOrder_Id'] = _rows[0].WorkOrder_Id
    },
    getRowProcess(_rows) {
      this.editFormFields['Process_Id'] = _rows[0].Process_Id
      this.editFormFields['ProcessCode'] = _rows[0].ProcessCode
      this.editFormFields['ProcessName'] = _rows[0].ProcessName
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
      this.detailOptions.buttons = []
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    getFormOption(field) {
      let option
      this.editFormOptions.forEach((x) => {
        x.forEach((item) => {
          if (item.field == field) {
            option = item
          }
        })
      })
      return option
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
      let process_Id = this.getFormOption('Process_Id')
      process_Id.hidden = true
      let WorkOrder_Id = this.getFormOption('WorkOrder_Id')
      WorkOrder_Id.hidden = true
      let Product_Id = this.getFormOption('Product_Id')
      // console.log(row);
      this.editFormFields.StandNumber = row.CrQuantity
      this.editFormFields.DisStandNumber = row.MajQuantity
      this.editFormFields.ScrapQty = row.MinQuantity
      Product_Id.hidden = true
      this.editFormOptions.forEach((item) => {
        item.forEach((x) => {
          //如果是编辑设置为只读
          if (x.field == 'ProcessCheckCode') {
            x.placeholder = '请输入，忽略将自动生成'
          }
        })
      })

      //判断报废数量
      if (this.currentAction == 'update') {
        if (this.editFormFields.ScrapQty > 0) {
          this.editFormOptions.forEach((item) => {
            item.forEach((x) => {
              if (x.field == 'reason') {
                x.hidden = false
                x.required = true
              }
            })
          })
        }
      }
    },
  },
}
export default extension
